package org.vudroid.core;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import org.vudroid.R;
import org.vudroid.core.ex3ndr.NookBaseActivity;
import org.vudroid.core.presentation.BrowserAdapter;
import org.vudroid.core.presentation.UriBrowserAdapter;

import java.io.File;
import java.io.FileFilter;

public abstract class BaseBrowserActivity extends Activity implements View.OnKeyListener
{
    private BrowserAdapter adapter;
    private static final String CURRENT_DIRECTORY = "currentDirectory";
    private final AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener()
    {
        @SuppressWarnings({"unchecked"})
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
        {
            final File file = ((AdapterView<BrowserAdapter>) adapterView).getAdapter().getItem(i);
            if (file.isDirectory())
            {
                setCurrentDir(file);
            }
            else
            {
                showDocument(file);
            }
        }
    };
    private UriBrowserAdapter recentAdapter;
    private ViewerPreferences viewerPreferences;
    protected final FileFilter filter;

    public BaseBrowserActivity()
    {
        this.filter = createFileFilter();
    }

    protected abstract FileFilter createFileFilter();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browser);
        viewerPreferences = new ViewerPreferences(this);
        final ListView browseList = initBrowserListView();
        final ListView recentListView = initRecentListView();
        createListeners();
        TabHost tabHost = (TabHost) findViewById(R.id.browserTabHost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("Browse").setIndicator("Browse").setContent(new TabHost.TabContentFactory()
        {
            public View createTabContent(String s)
            {
                return browseList;
            }
        }));
        tabHost.addTab(tabHost.newTabSpec("Recent").setIndicator("Recent").setContent(new TabHost.TabContentFactory()
        {
            public View createTabContent(String s)
            {
                return recentListView;
            }
        }));
    }

    private void createListeners()
    {
        Button openButton = (Button) findViewById(R.id.openbutton);
        openButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                ListView listView = (ListView) ((TabHost) findViewById(R.id.browserTabHost)).getCurrentView();
                listView.setEnabled(true);
                int index = listView.getSelectedItemPosition();
                if (index != ListView.INVALID_POSITION)
                {
                    listView.getChildAt(index).performClick();
                }
            }
        });

        Button upButton = (Button) findViewById(R.id.upButton);
        upButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                int currentIndex = adapter.getSelectedIndex();
                adapter.setSelectedIndex(currentIndex - 1 >= 0 ? currentIndex - 1 : 0);
            }
        });

        Button bottomButton = (Button) findViewById(R.id.bottomButton);
        bottomButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                int currentIndex = adapter.getSelectedIndex();
                adapter.setSelectedIndex(currentIndex + 1 % adapter.getCount());
                Intent intent = new Intent("com.bravo.intent.action.VIEW");
                
                final ListView listView = (ListView) ((TabHost) findViewById(R.id.browserTabHost)).getCurrentView();
                int index = listView.getSelectedItemPosition();
                final int nextSelected = index != ListView.INVALID_POSITION ? (index + 1) % listView.getCount() : 0;
                listView.post(new Runnable()
                {
                    public void run()
                    {
                        listView.setSelection(nextSelected);
                        listView.getSelectedView().setSelected(true);
                    }
                });
            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
        final File sdcardPath = new File("/");
        if (sdcardPath.exists())
        {
            setCurrentDir(sdcardPath);
        }
        else
        {
            setCurrentDir(new File("/"));
        }
        if (savedInstanceState != null)
        {
            final String absolutePath = savedInstanceState.getString(CURRENT_DIRECTORY);
            if (absolutePath != null)
            {
                setCurrentDir(new File(absolutePath));
            }
        }
    }

    private ListView initBrowserListView()
    {
        final ListView listView = new ListView(this);
        adapter = new BrowserAdapter(this, filter);
        listView.setAdapter(adapter);
        listView.setDrawSelectorOnTop(true);
        listView.setOnItemClickListener(onItemClickListener);
        listView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
        return listView;
    }

    private ListView initRecentListView()
    {
        ListView listView = new ListView(this);
        recentAdapter = new UriBrowserAdapter();
        listView.setAdapter(recentAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @SuppressWarnings({"unchecked"})
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
                showDocument(((AdapterView<UriBrowserAdapter>) adapterView).getAdapter().getItem(i));
            }
        });
        listView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
        return listView;
    }

    private void showDocument(File file)
    {
        showDocument(Uri.fromFile(file));
    }

    protected abstract void showDocument(Uri uri);

    private void setCurrentDir(File newDir)
    {
        adapter.setCurrentDirectory(newDir);
        getWindow().setTitle(newDir.getAbsolutePath());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putString(CURRENT_DIRECTORY, adapter.getCurrentDirectory().getAbsolutePath());
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        recentAdapter.setUris(viewerPreferences.getRecent());
    }

    public boolean onKey(View view, int i, KeyEvent keyEvent)
    {
        if (i == NookBaseActivity.NOOK_PAGE_DOWN_KEY_LEFT)
        {
            ListView listView = (ListView) ((TabHost) findViewById(R.id.browserTabHost)).getCurrentTabView();
            int index = listView.getSelectedItemPosition();
            int nextSelected = index != ListView.INVALID_POSITION ? (index + 1) % listView.getCount() : 0;
            listView.setSelection(nextSelected);
        }
        else if (i == NookBaseActivity.NOOK_PAGE_UP_KEY_LEFT)
        {
            ListView listView = (ListView) ((TabHost) findViewById(R.id.browserTabHost)).getCurrentTabView();
            int index = listView.getSelectedItemPosition();
            int nextSelected = index != ListView.INVALID_POSITION ? (index - 1) % listView.getCount() : 0;
            listView.setSelection(nextSelected);
        }

        return false;
    }
}
